import Vue from 'vue'
import { getToken } from '@/utils/auth'
import router from './router'
import store from './store'
// import localStorage from './utils/localStorage'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

import { buildMenus } from '@/api/system/menu'

// 第三方
import ElementUI from 'element-ui'
Vue.use(ElementUI) // permission controls

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login']

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    // 已登录且要跳转的页面是登录页
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      console.log(store)
      if (store.state.user.roles.length === 0) { // 判断当前用户是否已拉取完user_info 信息
        store.dispatch('GetInfo').then(res => { // 拉取user_info
          // 动态路由，拉取菜单
          loadMenus(next, to)
        }).catch(err => {
          console.log(err)
          store.dispatch('LogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      } else if (store.state.user.loadMenus) {
        // 登录时未拉取菜单， 在此处拉取
        store.dispatch('updateLoadMenus').then(res => {}) // 第一次进来后，先关闭拉取菜单开关
        loadMenus(next, to) // 拉取菜单
      } else {
        next()
      }
    }
  } else {
    /* has no token */
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }

  // 导航目标地址store存储
  store.dispatch('focusCurrentPage', to).then((item) => {
    store.dispatch('initTabsList') // 初始化tab列表
  })
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

export const loadMenus = (next, to) => {
  buildMenus().then(res => {
    store.dispatch('initRouteMenu', res.data.data.rules).then(() => {
      next({ ...to, replace: true })
    })
  })
}
